package com.inspur.sc.springboot.controller;

import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class IndexController {

    @GetMapping(value = "/login")
    public String login(HttpServletRequest request, Model model) {
        Object exception=request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        String error=request.getParameter("error");
        String expired=request.getParameter("expired");
         if(null == error && null ==expired ){
            return "login";
        }if(exception instanceof InternalAuthenticationServiceException){
            model.addAttribute("loginError", true);
            model.addAttribute("errorMsg", "用户已登录，请不要重复登录!");
            return "login";
        }else if(error != null) {
            model.addAttribute("loginError", true);
            model.addAttribute("errorMsg", "用户名或密码错误，请重新输入!");
            return "login";
        }else if(expired !=null){
            model.addAttribute("loginError", true);
            model.addAttribute("errorMsg", "登录会话失效，请重新登录!");
            return "login";
        }
        return "login";
    }

    @GetMapping("/")
    public void root(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("/login").forward(request,response);
    }

    @GetMapping("/403")
    public String authority()  {

        return "common/403";
    }

}
